import pandas as pd
# 将 pandas DataFrame 写入 CSV 文件
def saveToCSV(df_pd, fname):
    df_pd.to_csv(fname, encoding='utf-8', index=False)

def extract_maxcurrent():
    # 读取 CSV 文件为 pandas DataFrame
    pandasdf = pd.read_csv("dn_dws20230103.csv")
    print('清洗前的电流数据结构信息为：')
    pandasdf.info()
    # 将列名 "tableip" 重命名为 "ip"
    pandasdf.rename(columns={"tableip": "ip"}, inplace=True)
    # 删除重复列 'tableequipmentnumber'
    del pandasdf['tableequipmentnumber']
    # 删除空列 'datacollectionspecifictime'
    del pandasdf['datacollectionspecifictime']
    # 'threephasecurrentdata'列中的空值填充为 'A:0.0A,B:0.0A,C:0.0A'
    pandasdf['threephasecurrentdata'].fillna('A:0.0A,B:0.0A,C:0.0A', inplace=True)
    # 提取'threephasecurrentdata'列中的最大电流值，保存到新的列'maxcurrent'
    pandasdf['maxcurrent'] = pandasdf['threephasecurrentdata'].apply(lambda x: max(
        float(val.split(':')[1].replace('A', '')) for val in str(x).replace(';', ',').split(',')) )
    # 删除原始的'threephasecurrentdata'列
    del pandasdf['threephasecurrentdata']
    # 去除重复的设备编号和打包时间的记录
    pandasdf.drop_duplicates(subset=['equipmentnumber', 'packagetime'], inplace=True)
    print('清洗后的电流数据结构信息为：')
    pandasdf.info()
    return pandasdf

if __name__ == '__main__':
    # 执行提取最大电流值的操作
    df = extract_maxcurrent()
    # 保存处理后的数据到 CSV 文件
    saveToCSV(df, "a20230103.csv")